# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

from absl import app, flags
from coin.strategy.mm.simple_sim.runner import *


def main(argv):
  FLAGS = flags.FLAGS

  try:
    profile_name = argv[1]
    profile_args = argv[2:]
    profile = get_profile_module(profile_name, profile_args)
  except IndexError:
    sys.stderr.write('Usage: python -m %s.runner <profile>\n' % __package__)
    return 1
  except ModuleNotFoundError:
    return 2

  num_strategy_per_group = 32
  time_ranges = to_list(profile.get_time_ranges())

  results = []
  for from_ts, to_ts in time_ranges:
    # TODO(jaewon)
    num_strat = get_num_strategies(profile, from_ts, to_ts)
    num_group = int(math.ceil(num_strat / float(num_strategy_per_group)))
    step = int(math.ceil(num_strat / float(num_group)))

    for i in range(num_group):
      from_index = i * step
      to_index = (min(from_index + step - 1, num_strat - 1) if not FLAGS.test_run else from_index)

      if FLAGS.test_run and len(futures) != 0:
        continue

      logging.info('Initiating %s - %s: %d - %d',
                   to_datetime(from_ts),
                   to_datetime(to_ts),
                   from_index,
                   to_index)
      results += run_sim_strategy(profile_name,
                                  from_ts,
                                  to_ts,
                                  from_index,
                                  to_index,
                                  profile_args=profile_args,
                                  root_dir=FLAGS.flow_root_dir,
                                  from_feed_cache=FLAGS.feed_cache)
  profile.aggregate_result(results)


if __name__ == '__main__':
  logging.basicConfig(
      level='DEBUG',
      format='%(levelname)8s %(asctime)s %(name)s %(filename)s:%(lineno)d] %(message)s')
  logging.getLogger('coin.exchange.util.feed_checker').setLevel(logging.WARNING)

  flags.DEFINE_string('flow_root_dir',
                      None,
                      'If specified, use the specified directory as flow roor directory.')

  flags.DEFINE_bool('test_run', False, 'If true, it run only one strategy profile for testing.')

  flags.DEFINE_bool('feed_cache', False, 'Use feed cache.')

  app.run(main)
